<template>
	<view class="main">
		<view @click.capture="backList">
			<back-fixed :title="topTitle" :urlBack="urlBack" :isBack="isBack"></back-fixed>
		</view>
		<!-- <back-fixed title="新建专属码" urlBack="/pages/intel/index"></back-fixed> -->
		<view class="box">
			<view class="line_box">
				<view class="title">
					<span class="red">*</span>专属码类型
				</view>
				<view class="line" @click="huoma">
					<view class="line_title">
						{{typeCodeText}}
					</view>
					<view class="">
						<u-icon :name="typeArrow" size="40rpx" color="#CCCCCC"></u-icon>
					</view>
				</view>
			</view>

			<view class="line_box">
				<view class="flex row-between" style="background-color: #f8f8f8">
					<view class="title">
						<span class="red">*</span>专属码名称
					</view>
					<view class="numbers">
						{{codeNameLength}}/<span style="color: #999999;">30</span>
					</view>
				</view>
				<view class="inptStyle">
					<view class="">
						<u-input v-model="form.codeName" maxlength="30" :border="false"
							placeholder-style="color: #C1C1C1;font-size:32rpx" placeholder="请输入专属码名称"></u-input>
					</view>
				</view>
			</view>

			<view class="line_box">
				<view class="title" @click="tips('user')">
					<span class="red">*</span>使用成员<span style="display: inline-block;margin-left: 10rpx;"><u-image
							:src="wenhao" width="30rpx" height="30rpx"></u-image></span>
				</view>
				<view class="line">
					<!--start 成员标签组 -->
					<view style="width: 85%;" v-if="UserSelected.length >0">
						<scroll-view class="scroll-view_H" scroll-x="true">
							<view class="tags_box">
								<view class="tags" v-for="v,k in UserSelected" :key="v.nickName" @click="delUser(v,k)">
									<view class="tags_title">
										{{v.nickName}}
									</view>
									<view class="x_img">
										<u-image :src="x" width="36rpx" height="36rpx"></u-image>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<!--end 成员标签组 -->
					<view class="line_title" style="color:#C1C1C1 ;" v-if="UserSelected.length < 1">
						请选择团队成员
					</view>
					<view class="" @click="selUser">
						<u-icon :name="userArrow" size="40rpx" color="#CCCCCC"></u-icon>
					</view>
				</view>
			</view>

			<view class="line_box">
				<view class="title" @click="tips('mark')">
					扫码自动加标签<span style="display: inline-block;margin-left: 10rpx;"><u-image :src="wenhao" width="30rpx"
							height="30rpx"></u-image></span>
				</view>
				<view class="line">
					<!--start 自动标签组 -->
					<view style="width: 85%;" v-if="markChoose.length >0">
						<scroll-view class="scroll-view_H" scroll-x="true">
							<view class="tags_box">
								<view class="tags" v-for="v,k in markChoose" :key="v.tagName" @click="delMark(v,k)">
									<view class="tags_title">
										{{cultString(v.tagName)}}
									</view>
									<view class="x_img">
										<u-image :src="x" width="36rpx" height="36rpx"></u-image>
									</view>
								</view>
							</view>
						</scroll-view>
					</view>
					<!--end 自动标签组 -->
					<view class="line_title" style="color:#C1C1C1 ;" v-if="markChoose.length < 1">
						请选择标签
					</view>
					<view class="" @click="selMark">
						<u-icon :name="markArrow" size="40rpx" color="#CCCCCC"></u-icon>
					</view>
				</view>
			</view>

			<view class="line_box">
				<view class="title">
					自动通过好友
				</view>
				<view class="line">
					<view class="line_title">
						患者扫码添加自动通过验证
					</view>
					<view class="">
						<u-switch v-model="form.auto" active-color="#4DC0D9" inactive-color="#CCCCCC"></u-switch>
					</view>
				</view>
			</view>

			<view class="line_box" style="padding-bottom: 150rpx;">
				<view class="title">
					欢迎语
				</view>
				<view style="background-color: white;border-radius: 20rpx;">
					<u-input v-model="form.welcome" placeholder="请输入欢迎语..." maxlength="500" type="textarea" height="200"
						:auto-height="true" />
					<view
						style="text-align: right;color: #C1C1C1;border-radius: 20rpx;padding-right: 24rpx;padding-bottom: 24rpx;">
						{{welcomeLength}}/500
					</view>
				</view>
			</view>
		</view>
		<u-select v-model="showHuoma" :list="huomaList" @confirm="HuoMaConfirm" confirm-color="#4DC0D9"
			:safe-area-inset-bottom="true"></u-select>
		<u-popup v-model="showUser" mode="top" :safe-area-inset-bottom="true" :mask-close-able="false">
			<team-list @close="closeUser" @confirm="Userconfirm" :mytype="form.typeCodeValue"
				ref="teamChild" border-radius="40"></team-list>
		</u-popup>
		<u-popup v-model="showMark" border-radius="40" mode="top" z-index="20075" :safe-area-inset-bottom="false" :mask-close-able="false">
			<view>
				<view class="top_box">
					<view class="top_title">
						选择标签
					</view>
					<view class="x" @click="closeMark">
						<u-icon name="close" size="40rpx" color="#999999"></u-icon>
					</view>
				</view>
				<scroll-view scroll-y="true" style="height: 75vh;margin-top: 80rpx;">
					<view class="mark_zoom">
						<view class="mark_zoom_box" v-for="m,k in list" :key="m.id">
							<view class="mark_zoom_title">
								{{m.name}}
							</view>
							<view class="mark_zoom_item">
								<view class="disease" :class="{'checked':n.check}" @click="selectMarked(k,key)"
									v-for="n,key in m.tagList" :key="n.tagList.tagId">
									{{cultString(n.tagName)}}
								</view>
							</view>
						</view>
					</view>
					<empty-team title="暂无标签" v-if="empty"></empty-team>
					<u-loadmore :status="status" v-if="!empty" />
					<view class="sticky">
						<view class="btn_group">
							<view class="new_button" @click="newMark">
								新建标签组
							</view>
							<view class="my_button" @click="confirmMark">
								确认
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<bottom-button text="保存" :inactive="inactive" @confirm="saveCode"></bottom-button>
		<u-modal v-model="showBack" content="当前信息有变动，退出后修改过的 信息将丢失，确定要退出吗？" confirm-text="确认" confirm-color="#4DC0D9"
			:show-title="false" :show-cancel-button="true" @confirm="backConfirm" :cancel-style="{'borderRight':'1px solid #f8f8f8'}"></u-modal>
		<u-modal v-model="delShow" content="确定删除该标签组吗？" confirm-color="#4DC0D9" :show-cancel-button="true"
			confirm-text="确认" cancel-text="取消" @confirm="confirmDel" :cancel-style="{'borderRight':'1px solid #f8f8f8'}"></u-modal>
		<u-modal v-model="tipsShow" :title="tipsTitle" :content="Tipscontent" confirm-color="#4DC0D9"
			:show-cancel-button="false" confirm-text="确认"></u-modal>
	</view>
</template>

<script>
	import {
		getMarkLst,
		addHuocard,
		getEditData,
		putHuocard,
		teamCount
	} from '@/api/index.js'
	import pageMixin from '@/utils/pageMixin.js' // 在需要引入的组件中引入
	export default {
		mixins: [pageMixin],
		data() {
			return {
				urlBack: '',
				topTitle: '新建专属码',
				showBack: false,
				isBack: false,
				inactive: true,
				userArrow: 'arrow-down',
				markArrow: 'arrow-down',
				typeArrow: 'arrow-down',
				typeCodeText: '医生专属码', //单人团队专属码显示
				form: {
					codeName: '', //专属码名称
					auto: true, //自动加入
					welcome: '', //欢迎语
					typeCodeValue: '1', //单人团队专属码值
					mark: '',
				},
				huomaList: [{
					value: '1',
					label: '医生专属码'
				}, {
					value: '2',
					label: '团队专属码'
				}],
				showUser: false,
				showMark: false, //标签弹层
				showHuoma: false, //活动类型下拉菜单
				tipsShow: false,
				Tipscontent: '', //提示输入内容
				tipsTitle: '', //提示标题
				x: require('@/static/icon/x.png'),
				wenhao: require('@/static/icon/wenhao.png'),
				userList: [], //人员列表
				markChoose: [], //选中标签列表
				oldUserList: [],
				cardId: '', //修改还是添加
			}
		},
		watch: {
			typeCodeText: {
				async handler(val) {
					if (uni.getStorageSync('userinfo') && !this.cardId) {
						let name = uni.getStorageSync('userinfo').user.nickName
						let teamNum = await this.getTeamNum()
						if (val == '医生专属码') {
							this.form.welcome = `欢迎您关注${name}数字医生工作室！`
							this.form.codeName = `${name}数字医生工作室`
						}
						if (val == '团队专属码') {
							this.form.welcome = `欢迎您关注${name}团队数字医生工作室！`
							this.form.codeName = `${name}团队数字医生工作室${teamNum !== 0 ? teamNum : ''}`
						}
					}
				},
				immediate: true
			},
			showHuoma(nev) {
				if (nev) {
					this.typeArrow = 'arrow-up'
				} else {
					this.typeArrow = 'arrow-down'
				}
				//return 'arrow-down'
			},
			showUser(nev) {
				if (nev) {
					this.userArrow = 'arrow-up'
				} else {
					this.userArrow = 'arrow-down'
				}
			},
			showMark(nev) {
				if (nev) {
					this.markArrow = 'arrow-up'
				} else {
					this.markArrow = 'arrow-down'
				}
			},
			form: {
				handler(newVal, oldVal) {
					//console.log(newVal,'999');
					if (this.UserSelected.length > 0 && this.form.codeName.length > 0) {
						this.inactive = false
					} else {
						this.inactive = true
					}
				},
				deep: true, // 是否深度监听
				immediate: false, // 是否在组件创建时立即执行回调函数
			},
			UserSelected(newVal, oldVal) {
				//console.log(newVal, '111');
				if (newVal.length > 0 && this.form.typeCodeValue == 1 && !this.cardId) {
					this.form.welcome = `欢迎您关注${newVal[0].nickName}数字医生工作室！`
					this.form.codeName = `${newVal[0].nickName}数字医生工作室`
				}
				if (this.UserSelected.length > 0 && this.form.codeName.length > 0) {
					this.inactive = false
				} else {
					this.inactive = true
				}
			}
		},
		onLoad(obj) {
			if (obj.cardId && obj.cardId.length > 0) {
				this.cardId = obj.cardId
				this.urlBack = `/pages/intel/details?cardId=${this.cardId}`
				//console.log(this.cardId);
				this.$nextTick(() => {
					this.Getedit(this.cardId)
				})
				return
			}
			this.urlBack = `/pages/intel/index`
		},
		mounted() {
			// if (this.cardId.length > 0) {
			// 	this.Getedit(this.cardId)
			// }
		},
		computed: {
			UserSelected() {
				const arr = this.userList.filter(v => v.check == true)
				return arr
			},
			welcomeLength() {
				if (this.form.welcome !== null) {
					return this.form.welcome.length
				}
				return 0
			},
			codeNameLength() {
				return this.form.codeName.length
			},
			cultString(val) {
				return (val) => {
					if (!val) return ''
					const word = val.toString()
					if (word.length > 5) {
						return word.slice(0, 5) + '...'
					} else {
						return word
					}
				}
			}
		},
		methods: {
			async getTeamNum() {
				let res = await teamCount()
				console.log(res);
				return res.data
			},
			backList() { //后退
				this.isBack = false
				this.showBack = true
			},
			backConfirm() {
				uni.redirectTo({
					url: this.urlBack
				})
			},
			async getMyList(obj) {
				let res = await getMarkLst({
					'groupType': 0,
					...obj
				}) //全部：0，医院标签：1，科室标签：2
				//console.log(res);
				res.rows.map(v => {
					v.tagList.forEach(val => {
						val.check = false
					})
				})
				return res
			},
			tips(question) {
				this.tipsShow = true
				if (question == 'user') {
					this.tipsTitle = '使用成员说明' //提示输入内容
					this.Tipscontent = '医生专属码支持一个团队成员，患者 扫码添加对应成员' //提示标题
				}
				if (question == 'mark') {
					this.tipsTitle = '扫码自动加标签说明' //提示输入内容
					this.Tipscontent = '患者扫码添加后自动添加标签' //提示标题
				}
			},
			newMark() { //标签弹层新建按钮
				this.showMark = false
				uni.navigateTo({
					url: '/pages/intel/markGroup'
				})
			},
			closeMark() { //标签弹层X
				this.markChoose = this.list.reduce((pre, value, index) => {
					const checkList = value.tagList.filter((v, k) => v.check == true)
					pre.push(...checkList)
					return pre
				}, [])
				this.showMark = false
			},
			selectMarked(k, key) { //标签选中效果
				this.list[k].tagList[key].check = !this.list[k].tagList[key].check
			},
			delMark(value, key) { //删除标签
				this.list.map(v => {
					return v.tagList.map(val => {
						if (val == value) {
							val.check = false
						}
						return val
					})
				})
				this.markChoose.splice(key, 1)
			},
			confirmMark() { //标签弹层确认按钮
				this.markChoose = this.list.reduce((pre, value, index) => {
					const checkList = value.tagList.filter((v, k) => v.check == true)
					pre.push(...checkList)
					return pre
				}, [])
				this.showMark = false
			},
			selUser() { //人员弹层
				//this.$refs.teamChild.list = this.userList
				if (this.cardId.length > 0) {
					if (this.form.typeCodeValue == 1) {
						this.$u.toast('活动类型为医生专属码时不可修改')
						return
					}
				}
				this.showUser = true
			},
			closeUser(val) { //人员弹层X关闭
				//this.oldUserList = val  
				this.userList = val //选中人员   g改
				//console.log(this.userList,'111',val,'222');
				this.showUser = false
			},
			selMark() { //标签弹出
				if (this.list.length == 0) {
					this.clearPageStatus()
					this.getTeam()
				}
				this.showMark = true
			},
			huoma() { //专属码弹层
				if (this.cardId.length > 0) {
					this.$u.toast('专属码类型无法修改')
					return
				}
				this.showHuoma = true
			},
			HuoMaConfirm(e) {
				this.typeCodeText = e[0].label
				this.form.typeCodeValue = e[0].value
				//console.log(e);
			},
			delUser(value, key) { //删除人员tags
				if (this.cardId.length > 0) {
					if (this.form.typeCodeValue == 1) {
						this.$u.toast('活动类型为医生专属码时不可修改')
						return
					}
				}

				this.userList.forEach(v => {
					if (value == v) {
						v.check = false
					}
				})
				//this.$refs.teamChild.list[key].check = !this.$refs.teamChild.list[key].check
				//console.log(this.$refs.teamChild.list,key,value);
			},
			Userconfirm(list) {
				this.userList = this.$u.deepClone(list) //选中人员
				//console.log(list);
				this.showUser = false
			},
			GetMarkReS(res) {
				if (res.data.tagId && res.data.tagId !== undefined) {
					const arr = res.data.tagId.split(',')
					this.$nextTick(() => {
						this.list.map(v => {
							v.tagList.forEach(val => {
								if (arr.includes(val.tagId)) {
									//console.log(val,123);
									val.check = true
								}
							})
							return v
						})
						this.markChoose = this.list.reduce((pre, value, index) => {
							const checkList = value.tagList.filter((v, k) => v.check == true)
							pre.push(...checkList)
							return pre
						}, [])
					})
				}
			},
			async Getedit() { //修改回显
				// form: {
				// 	codeName: '', //专属码名称
				// 	auto: true, //自动加入
				// 	welcome: '', //欢迎语
				// 	typeCodeValue: '2', //单人团队专属码值
				// 	mark: '',
				// },
				this.topTitle = '修改专属码'
				let res = await getEditData(this.cardId)
				if (res.data.cardType && res.data.cardType !== undefined) { //form表单专属码类型
					this.form.typeCodeValue = res.data.cardType
					this.typeCodeText = this.huomaList.find(v => v.value == res.data.cardType).label
				}
				this.form.codeName = res.data.cardName //专属码名称
				this.$nextTick(() => {
					const myList = this.$refs.teamChild.list //使用成员
					res.data.qrSysUsers.forEach(v => {
						//console.log(v.userId,'1111' );
						myList.forEach(val => {
							//console.log(v.userId , val.userId);
							if (v.userId == val.userId) {
								val.check = true
							}
						})
					})
					this.userList = this.$u.deepClone(myList)
					//console.log(this.userList, myList);
				})
				//console.log(myList, 'teamChild',myList.length);
				this.GetMarkReS(res)
				//await this.GetMarkReS(res)
				const t = setTimeout(() => {
					clearTimeout(t)
					this.GetMarkReS(res)
				}, 1000)
				const r = setTimeout(() => {
					clearTimeout(r)
					this.GetMarkReS(res)
				}, 3000)
				this.form.auto = res.data.autoAdd == 1 ? true : false
				this.form.welcome = res.data.welcomeSpeech
				//console.log(res, '修改');
			},
			isPass() {
				if (this.form.codeName.length < 1) {
					this.$u.toast('请填写专属码名称')
					return false
				}
				if (this.UserSelected.length < 1) {
					this.$u.toast('请选择使用成员')
					return false
				}
				return true
			},
			async saveCode() {
				// form: {
				// 	codeName: '', //专属码名称
				// 	auto: true, //自动加入
				// 	welcome: '', //欢迎语
				// 	typeCodeValue: '1', //单人团队专属码值
				// 	mark: '',
				// },
				//userList: [], //人员列表
				//markChoose: [], //选中标签列表
				if (!this.isPass()) return //校验
				const params = {
					'autoAdd': this.form.auto ? 1 : 0,
					'cardName': this.form.codeName, //专属码名称
					'cardType': Number(this.form.typeCodeValue), //专属码类型（1单人 2多人
					'qrSysUsers': [
						// {userId:'',userName:'',wechatUserId:''}
					],
					'tagId': '',
					'welcomeSpeech': this.form.welcome
				}
				params.qrSysUsers = this.UserSelected.map(v => {
					return {
						'userId': v.userId,
						'userName': v.nickName,
						'wechatUserId': v.wechatUserId
					}
				})
				const tagId = this.markChoose.reduce((pre, value, index) => {
					pre.push(value.tagId)
					return pre
				}, [])
				params.tagId = tagId.join()
				//return
				if (this.cardId.length > 0) {
					let res = await putHuocard({
						...params,
						'cardId': this.cardId
					})
					if (res.code == 200) {
						uni.redirectTo({
							url: this.urlBack,
						})
					}
					return
				}
				let res = await addHuocard(params)
				if (res.code == 200) {
					uni.redirectTo({
						url: '/pages/intel/index'
					})
				}
				//console.log(123, params, res);
			}
		},
	}
</script>

<style lang="scss" scoped>
	.main {
		background-color: #F8F8F8;
		padding-bottom: 40rpx;

		.box {
			//margin-top: 30rpx;
			padding: 200rpx 24rpx 0 24rpx;
		}

		.line_box {
			margin-bottom: 40rpx;
			//margin: 0 24rpx;
			.line {
				background-color: white;
				padding: 28rpx 24rpx;
				border-radius: 20rpx;
				display: flex;
				justify-content: space-between;

				.line_title {
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 32rpx;
					color: #333333;
					line-height: 38rpx;
				}
			}

			.inptStyle {
				background-color: white;
				padding: 10rpx 24rpx 10rpx 24rpx;
				border-radius: 20rpx;
			}
		}

		.sticky {
			width: 100%;
			padding: 20rpx 24rpx 30rpx 24rpx;
			position: fixed;
			z-index: 1000;
			bottom: 0;
			padding-bottom: 80rpx;
			background-color: #FFFFFF;

			.btn_group {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.my_button {
					flex-shrink: 0;
					background-color: #4DC0D9;
					font-family: PingFang SC, PingFang SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #FFFFFF;
					line-height: 38rpx;
					text-align: center;
					padding: 20rpx 138rpx;
					border-radius: 20rpx;
				}

				.new_button {
					flex-shrink: 0;
					background-color: #A6DFEC;
					font-family: PingFang SC, PingFang SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #4DC0D9;
					line-height: 38rpx;
					text-align: center;
					padding: 20rpx 90rpx;
					border-radius: 20rpx;
				}
			}
		}

	}

	.mark_zoom {
		//padding: 0 24rpx 0 24rpx;

		.mark_zoom_box {
			display: flex;
			flex-direction: column;
			margin-bottom: 60rpx;

			.mark_zoom_title {
				font-family: PingFang SC, PingFang SC;
				font-weight: bold;
				font-size: 32rpx;
				color: #212121;
				line-height: 38rpx;
				margin-bottom: 20rpx;
				padding-left: 24rpx;
			}

			.mark_zoom_item {
				display: flex;
				flex-wrap: wrap;
				//justify-content: space-between;
				//align-content: center;
				padding-left: 24rpx;

				.disease {
					width: 220rpx;
					height: 80rpx;
					text-align: center;
					background: #F2F2F2;
					border-radius: 12rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 30rpx;
					color: #333333;
					line-height: 75rpx;
					//padding: 20rpx 80rpx;
					margin-bottom: 20rpx;
					margin-right: 22rpx;
				}
			}

			.checked {
				color: #4DC0D9 !important;
				background-color: #A6DFEC !important;
				border: 2rpx solid #4DC0D9;
			}
		}
	}

	.title {
		font-family: PingFang SC, PingFang SC;
		font-weight: bold;
		font-size: 32rpx;
		color: #212121;
		line-height: 38rpx;
		background-color: #F8F8F8;
		padding-bottom: 12rpx;
	}

	.tags_box {
		display: flex;
		font-weight: 500;
		font-size: 32rpx;
		color: #333333;
		line-height: 38rpx;

		//height: 60rpx;
		.tags {
			background: #F2F2F2;
			border-radius: 12rpx;
			margin-right: 40rpx;
			position: relative;
			flex-shrink: 0;

			.tags_title {
				padding: 8rpx 36rpx;
			}

			.x_img {
				position: absolute;
				top: 0;
				right: -20rpx;
			}
		}
	}

	.top_box {
		position: relative;
		padding-top: 40rpx;

		//background-color: white;
		.top_title {
			position: absolute;
			width: 100%;
			font-family: PingFang SC, PingFang SC;
			font-weight: bold;
			font-size: 32rpx;
			color: #212121;
			line-height: 38rpx;
			text-align: center;
			z-index: 2;
		}

		.x {
			position: absolute;
			right: 40rpx;
			z-index: 2;
		}
	}

	.numbers {
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 28rpx;
		color: #4DC0D9;
		line-height: 33rpx;
	}

	.red {
		color: #F1280D;
	}
</style>